// Copyright 2022 Tencent
#include "base/log.h"
#include "util/json.h"
namespace net_tools::util
{

  Json::Json()
      : ifs_(nullptr),
        ofs_(nullptr),
        write_(nullptr),
        read_(nullptr)
  {
    ::Json::StreamWriterBuilder writerbuilder;
    write_ = writerbuilder.newStreamWriter();
    ::Json::CharReaderBuilder readerbuilder;
    read_ = readerbuilder.newCharReader();
  }
  Json::~Json()
  {
    if (ifs_)
    {
      if (ifs_->is_open())
      {
        ifs_->close();
      }
      delete ifs_;
      ifs_ = nullptr;
    }
    if (ofs_)
    {
      if (ofs_->is_open())
      {
        ofs_->close();
      }
      delete ofs_;
      ofs_ = nullptr;
    }
    delete write_;
    delete read_;
  }
  bool Json::Open_read(const std::string &address)
  {
    if (ifs_)
    {
      delete ifs_;
      ifs_ = nullptr;
    }
    ifs_ = new std::ifstream(address.c_str());
    return ifs_->is_open();
  };
  bool Json::Open_write(const std::string &address)
  {
    if (ofs_)
    {
      delete ofs_;
      ifs_ = nullptr;
    }
    ofs_ = new std::ofstream(address.c_str());
    return ofs_->is_open();
  };
  void Json::Json_write(::Json::Value *root)
  {
    write_->write(*root, ofs_);
  };
  void Json::Read_from_ifs(::Json::Value *root)
  {
    std::stringstream ss;
    ss << ifs_->rdbuf();
    std::string json = ss.str();
    read_->parse(json.c_str(), json.c_str() + json.length(), root, nullptr);
  };

} // namespace net_tools::base